package com.tom.cfg;

import com.tom.convertor.DateConvertor;
import com.tom.interceptor.MyInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.format.FormatterRegistry;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.nio.charset.StandardCharsets;
import java.util.List;

@ComponentScan({"com.tom.controller", "com.tom.interceptor","com.tom.convertor"})
@EnableWebMvc
public class SpringMVCConfig implements WebMvcConfigurer {

    @Autowired
    private DateConvertor dateConvertor;

    @Autowired
    private MyInterceptor myInterceptor;

    /**
     * 1:解决静态资源被DispatcherServlet拦截问题
     * 类似于 <mvc:default-servlet-handler/>
     *
     * @param configurer
     */
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }


    /**
     * 2:解决响应乱码问题
     *
     * @param converters
     */
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {

        StringHttpMessageConverter messageConverter = new StringHttpMessageConverter();
        messageConverter.setDefaultCharset(StandardCharsets.UTF_8);
        converters.add(messageConverter);

        MappingJackson2HttpMessageConverter jackson = new MappingJackson2HttpMessageConverter();
        jackson.setDefaultCharset(StandardCharsets.UTF_8);
        converters.add(jackson);
    }

    /**
     * 3:添加拦截器
     *
     * @param registry
     */

    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(myInterceptor)
                .addPathPatterns("/**")
                .excludePathPatterns("/assets/**");

    }


    /**
     * 4:文件上传处理
     *
     * @return
     */
    @Bean
    public CommonsMultipartResolver multipartResolver() {
        CommonsMultipartResolver resolver = new CommonsMultipartResolver();
        resolver.setDefaultEncoding("UTF-8");
        return resolver;
    }


    /**
     * 5:添加转换器
     *
     * @param registry
     */
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverter(dateConvertor);
    }

}
